package com.example.sunweihao;

import java.util.ArrayList;
import java.util.List;

public class ViewGroup extends View {
    //孩纸列表
    List<View> childList = new ArrayList<>();
    //孩纸数组
    private View[] mChildren = new View[0];

    /**
     * 添加View
     *
     * @param view 子view
     */
    public void add(View view) {
        //判断view是否为空
        if (view == null) {
            return;
        }
        //添加View
        childList.add(view);
        //toArray排序数组
        mChildren = (View[]) childList.toArray(new View[childList.size()]);
    }

    //事件分发入口
    public boolean dispatchTouchEvent(MotionEvent event) {
        //是否拦截
        boolean intercepted = onInterceptTouchEvent(event);
        //事件类型
        int actionMasked = event.getActionMasked();
        //如果事件为cancel事件或者是不拦截，&&表示后面的会执行，而&表示后面的不会执行
        if (actionMasked != MotionEvent.ACTION_CANCEL && !intercepted) {
            //如果是DOWN事件
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                final View[] children = this.mChildren;//为子控件赋值
                //对子控件进行遍历 减：耗时，概率大一些
                for (int i = children.length-1; i >=0 ; i--) {
                    View child = mChildren[i];
                    //View能够接收事件
                    if (child.isContainer(event.getX(),event.getY())){
                        continue;
                    }
                    //能够接收事件 child 分发给他
                    if (dispatchTransformedTouchEvent(event,child)) {

                    }
                }
            }
        }
    }
    //分发处理 子控件 View
    private boolean dispatchTransformedTouchEvent(MotionEvent event, View child) {
        final boolean handled;
        handled=child.dispatchTouchEvent(event);
        return false;
    }

    /**
     * 是否拦截触摸事件
     *
     * @param ev
     * @return
     */
    private boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }
}
